<?php
//写入文件
require "../config.php";
require "./user_authentication.php";
$user_name = $_POST['id']; //用户名
$Token = $_POST['Token']; //用户token
$userTime = $_POST['userTime']; //用户时间
$txt = $_POST['txt'];
$file_title = $_POST['title'];
$file_name = $_POST['file_name'];
$status_json = json_decode(user_authentication($user_name,$Token,$userTime),true); //用户登录验证
if($status_json['status']=="200"){
    $conn = mysqli_connect($MySqlHost, $MySqlUser, $MySqlPwd, $MySqlDatabaseName);
    if (mysqli_connect_errno($conn))
    {
        echo json_encode(array("status"=>"500", "msg" => "连接 MySQL 失败: " . mysqli_connect_error()));
    }
    mysqli_query($conn, "set character set 'utf8'");//读库
    mysqli_query($conn, "set names 'utf8'");//写库
    $res = mysqli_query($conn,"SELECT * FROM files WHERE possessor = '$user_name' AND file_name = '$file_name'");
    if(mysqli_num_rows($res)>0){
        //修改文件
        $fp = fopen("Files/".$file_name , "w");
        fwrite($fp,$txt);
        fclose($fp);
        $res = mysqli_query($conn,"UPDATE files SET file_title = '$file_title' WHERE possessor = '$user_name' AND file_name = '$file_name'");
        echo json_encode(array("status"=>200, "msg" => "保存成功" ,"file_name"=>$file_name , "time"=> time()));
    }else{
        //新建文件
        do{
            $new_file_name = rand(100000,999999);
            $res = mysqli_query($conn,"SELECT * FROM files WHERE file_name = '$new_file_name'");
        }while(mysqli_num_rows($res) != 0);
        $fp = fopen("Files/".$new_file_name , "w");
        $file_time = time();
        $file_title = "你好云存";
        $res = mysqli_query($conn,"INSERT INTO files (file_name,possessor,file_title,file_type,file_time,file_pwd) 
VALUES('$new_file_name','$user_name','$file_title','html','$file_time','')");
        fwrite($fp,"欢迎使用云存!");
        fclose($fp);
        echo json_encode(array("status"=>200, "msg" => "新建文件成功" ,"data" => array("file_name" => $new_file_name, "possessor" => $user_name,"file_title" => $file_title,"file_type" => 'html',"file_time" => $file_time,"file_pwd" => ''), "time"=> time()));
    }
    mysqli_close($conn);
}else{
    echo($status_json['status'] . "_" . $status_json['msg'] . "_" . $status_json['time']);
}
